package com.liwei.servlet;

import com.liwei.model.User;
import org.springframework.context.ApplicationContext;

import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Liwei on 2015/11/1.
 */
// @WebServlet(name = "helloServlet",urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Servlet 是单例还是多例呢？ ");
        /**
         * 【实验证明】： Servlet 的构造器在第 1 次 访问的时候创建
         * 后续再调用这个请求的时候不再实例化
         * 【这个结论很重要】
         */
        int hashCode = this.hashCode();
        System.out.println("this.hashCode() " + hashCode);

        // super.doGet(req, resp);
        //1、 从 application 域对象中得到 IOC 容器的引用
        ServletContext servletContext = getServletContext();
        ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
        //2、 从 IOC 容器中得到需要的 bean
        User user = (User) ctx.getBean("user");
        System.out.println("Web 项目集成 Spring 要配置监听器。。。");
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
    }

    public HelloServlet() {
        System.out.println("------------ HelloServlet 的构造器 ------------");
    }
}
